-- input_manager.lua
-- 输入管理器 - 纯逻辑管理，不注册到场景

local InputManager = {}
InputManager.__index = InputManager

function InputManager.new()
    local instance = {
        keyboardInput = nil,    -- 键盘输入系统
        currentContext = "Game", -- 当前输入上下文
        callbacks = {},          -- 输入回调函数
        -- 统一的按键映射
        keyMappings = {
            -- 移动控制
            Up = {"W", "Up"},
            Down = {"S", "Down"},
            Left = {"A", "Left"},
            Right = {"D", "Right"},
            Jump = {"Space"},
            Attack = {"J"},
            Sprint = {"Shift"},
            Roll = {"Shift"},    -- 添加翻滚按键映射
            Menu = {"Escape"},
            Confirm = {"Return", "Space"},
            Cancel = {"Escape"}
        }
    }
    return setmetatable(instance, InputManager)
end

-- 设置键盘输入系统
function InputManager:setKeyboardInput(keyboardInput)
    self.keyboardInput = keyboardInput
end

-- 切换到指定上下文
function InputManager:pushContext(contextName)
    self.currentContext = contextName
    print("输入上下文切换到: " .. contextName)
end

-- 弹出当前上下文
function InputManager:popContext()
    self.currentContext = "Game"
    print("输入上下文弹出，当前上下文: Game")
end

-- 获取当前上下文
function InputManager:getCurrentContext()
    return self.currentContext
end

-- 注册输入回调
function InputManager:onInput(actionName, callback, context)
    context = context or self.currentContext
    if not self.callbacks[context] then
        self.callbacks[context] = {}
    end
    if not self.callbacks[context][actionName] then
        self.callbacks[context][actionName] = {}
    end
    table.insert(self.callbacks[context][actionName], callback)
end

-- 更新输入管理器
function InputManager:update(dt)
    -- 更新键盘输入系统
    if self.keyboardInput then
        self.keyboardInput:update(dt)
    end
end

-- 检查动作是否激活
function InputManager:isActionActive(actionName)
    if self.keyboardInput then
        local keys = self.keyMappings[actionName]
        if keys then
            for _, key in ipairs(keys) do
                if self.keyboardInput:isKeyPressed(key) then
                    return true
                end
            end
        end
    end
    return false
end

-- 检查动作是否刚刚按下
function InputManager:isActionJustPressed(actionName)
    if self.keyboardInput then
        local keys = self.keyMappings[actionName]
        if keys then
            for _, key in ipairs(keys) do
                if self.keyboardInput:isKeyJustPressed(key) then
                    return true
                end
            end
        end
    end
    return false
end

-- 获取原始键盘输入
function InputManager:getRawKeyboardInput()
    return self.keyboardInput
end

return InputManager